import { showToast } from 'vant';
import type { RouteRecordRaw } from 'vue-router';
import {
  createRouter,
  createWebHistory,
} from 'vue-router';

import { useUserStore } from '../stores/user';

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/LoginView.vue'),
    meta: { requiresAuth: false, title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/login/RegisterView.vue'),
    meta: { requiresAuth: false, title: '注册' }
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/home/HomeView.vue'),
    meta: { requiresAuth: true, title: '首页' }
  },
  {
    path: '/exam-list',
    name: 'ExamList',
    component: () => import('../views/exam/ExamListView.vue'),
    meta: { requiresAuth: true, title: '考试列表' }
  },
  {
    path: '/exam-detail/:id',
    name: 'ExamDetail',
    component: () => import('../views/exam/ExamDetailView.vue'),
    meta: { requiresAuth: true, title: '考试详情' }
  },
  {
    path: '/exam/:id',
    name: 'Exam',
    component: () => import('../views/exam/ExamView.vue'),
    meta: { requiresAuth: true, title: '考试进行中' }
  },
  {
    path: '/result/:id',
    name: 'ExamResult',
    component: () => import('../views/exam/ExamResultView.vue'),
    meta: { requiresAuth: true, title: '考试结果' }
  },
  {
    path: '/exam/:id/ranking',
    name: 'ExamRanking',
    component: () => import('../views/exam/ExamRankingView.vue'),
    meta: { requiresAuth: true, title: '考试排名' }
  },
  {
    path: '/history',
    name: 'History',
    component: () => import('../views/history/HistoryView.vue'),
    meta: { requiresAuth: true, title: '历史记录' }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('../views/profile/ProfileView.vue'),
    meta: { requiresAuth: true, title: '个人信息' }
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/error/NotFoundView.vue'),
    meta: { requiresAuth: false, title: '页面不存在' }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = `${to.meta.title || '考试系统'}`
  
  const userStore = useUserStore()
  const requiresAuth = to.meta.requiresAuth
  
  console.log('路由守卫检查:', {
    from: from.path,
    to: to.path,
    requiresAuth,
    isLoggedIn: userStore.isLoggedIn,
    hasToken: !!userStore.token
  })
  
  // 需要登录但未登录
  if (requiresAuth && !userStore.isLoggedIn) {
    console.log('需要登录但未登录，重定向到登录页')
    showToast('请先登录')
    next({ name: 'Login', query: { redirect: to.fullPath } })
    return
  }

  // 已登录但访问登录页
  if (userStore.isLoggedIn && (to.name === 'Login' || to.name === 'Register')) {
    console.log('已登录但访问登录页，重定向到首页')
    next({ name: 'Home' })
    return
  }

  next()
})

export default router
